<?php
namespace app\gacj\model;
use think\Model as ThinkModel;

/**
 * 项目模型
 * @package app\gacj\model
 */
class User extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'gacj_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //获取投票信息
    public static function getInfo($id){
        $result = self::where('status', 1)->get($id);
        if(!$result){
            return;
        }
        //处理时间
        if ($result['create_time']) {
            $result['create_time_format'] = date('Y-m-d H:i:s', $result['create_time']);
        }
        if ($result['update_time']) {
            $result['update_time_format'] = date('Y-m-d H:i:s', $result['update_time']);
        }
        return $result;
    }

    /**
     * 获取文档列表
     * @param array $map 筛选条件
     * @param array $order 排序
     * @author rocky
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($map = [], $order = 'id desc', $paginate=true)
    {
        if($paginate){
            $list = self::where($map)->order($order)->paginate();
        }else{
            $list = self::where($map)->order($order)->select();
        }

        if(!$list){
            return;
        }

        foreach($list as $k=>&$v){
            //处理时间
            if ($v['create_time']) {
                $v['create_time_format'] = date('Y-m-d H:i:s', $v['create_time']);
            }
            if ($v['update_time']) {
                $v['update_time_format'] = date('Y-m-d H:i:s', $v['update_time']);
            }
        }

        return $list;
    }

    public static function addUser($user) {
        if(!$user) return;

        $info = self::where('openid', $user->id)->find();
        if($info) return $info;

        $data['openid'] = $user->id;
        $data['nickname'] = $user->nickname;
        $data['avatar'] = $user->avatar;

        $data['sex'] = $user->original['sex'] ?? '';
        $data['city'] = $user->original['city'] ?? '';
        $data['province'] = $user->original['province'] ?? '';
        $data['country'] = $user->original['country'] ?? '';
        $data['language'] = $user->original['language'] ?? '';
        $data['unionid'] = $user->original['unionid'] ?? '';

        $data['status'] = 1;
        $data['create_time'] = time();

        if($data['id'] = self::insertGetId($data)){
            return $data;
        }

        return;
    }
}
